package plantshop.server;
import java.io.IOException;
import java.io.Serializable;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

import plantshop.model.Client;


public class Server implements Serializable{
	/**
	 * 
	 */
	private static final long serialVersionUID = -7553521504022536773L;

	public static void main(String[] args) throws IOException, InterruptedException {

		final int PORT = 9876;

		ServerSocket serverSocket = null;
		List<Client> clients = new ArrayList<Client>();

		System.out.println("Server IP address: " + InetAddress.getLocalHost().getHostAddress());

		try {
			serverSocket = new ServerSocket(PORT);
			System.out.print("Listening for inbound connection on port " + PORT + "... ");
		} catch (IOException e) {
			System.err.println("Could not listen on port: " + PORT + ". error: " + e);
			System.exit(1);
		}

		List<Client> currClients = null;
		boolean gameStarted;
		Thread t = new ServerListenThread(serverSocket, clients);
		t.start();
		while(true){
			gameStarted = false;
			while(!gameStarted){
				if(!t.isAlive()){
					gameStarted = true;
					currClients = clients;
					clients = new LinkedList<Client>();
					t = new ServerListenThread(serverSocket, clients);
					t.start();
				}
			}
			new ServerCommunicateThread(currClients).start();
		}

	}
}

